<template>
	<div ref="mChartWpRef" class="m-chart-wp" :style="{height: props.height}">
		<div class="m-chart" ref="chartRef"></div>
	</div>
</template>

<script setup>
	import { reactive, ref, watch, onMounted, onBeforeUnmount } from 'vue'
	import { useSlots, useAttrs } from 'vue'
	import * as echarts from 'echarts';

	const attrs = useAttrs();

	const mChartWpRef = ref(null);
	const chartRef = ref(null);

	const emit = defineEmits(['click']);

	const props = defineProps({
		height: {
			type: String,
			default: '100%'
		},
		options: {
			type: Object
		}
	})

	var myChart = null;

	// 监听options变化
	watch(() => props.options, () => {
		initChart();
	}, {
		deep: true
	})

	onMounted(() => {
		initChart();

		// 监听尺寸变化
		window.addEventListener('resize', debResize);
	})

	onBeforeUnmount(() => {
		if(myChart) {
			myChart.off('click', handleClick);
	    myChart.dispose();
	    myChart = null;
		}

		// 移除页面尺寸监听
		window.removeEventListener('resize', debResize);
	})

	let timer = null;
	function debResize() {
		clearTimeout(timer);
		timer = setTimeout(() => {
			if(myChart) {
				myChart.resize();
			}
		}, 100);
	}

	function initChart() {
		if(!props.options) {
			return;
		}
		if(!myChart) {
			myChart = echarts.init(chartRef.value);
			myChart.on('click', handleClick);
		}
    myChart.setOption(props.options, true);
  }

  function handleClick(params) {
    emit('click', params);
  }

</script>

<style lang="less" scoped>
.m-chart-wp {
	width: 100%;
	.m-chart {
		width: 100%;
		height: 100%;
	}
}
</style>